/**
 * FileUpLoadController
 *
 * @description :: Server-side logic for managing fileuploads
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {
	upload: function(req, res){
		res.setTimeout(0);// 0 => infinite
		req.file('avatar')
			.upload({
				maxBytes: 1000000 // in bytes
			}, function whenDone(err, uploadedFiles){
				if(err){
					return res.negotiate(err);	
				} 
				else if(uploadedFiles.length === 0){
					return res.badRequest("No file was uploaded");
				}
				else {
					return res.json({
						files:uploadedFiles,
						textparams:req.params.all()
					});
				}
			});
	},
	uploadGridFS: function(req, res){
		req.file('avatar').upload({
			adapter: require('skipper-gridfs'),
			uri: 'mongodb://@localhost:27017/sails_ship.avatar_uploads'
		},function whenDone(err,uploadedFiles){
			if(err) return res.negotiate(err);
			return res.ok({
			    files: uploadedFiles,
			    textParams: req.params.all()
			  });
		})
	},
	download: function(req, res){
		require('fs').createReadStream(req.param('path'))
			.on('error', function(err){
				return res.serverError(err);
			})
			.pipe(res);
	}
};

